package org.example.fileClient;

import io.netty.bootstrap.Bootstrap;
import io.netty.buffer.Unpooled;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;
import io.netty.util.CharsetUtil;

import java.io.*;

/**
 * @classname: Client
 * @description: TODO
 * @author: kaiser
 * @date: 2024/3/16 17:46
 * @version: 1.0
 */
public final class Client {
    public static void main(String[] args) throws Exception {
        init("127.0.0.1", 8888);
    }

    public static void init(String host, int port) throws Exception {
        EventLoopGroup group = new NioEventLoopGroup();
        try {
            Bootstrap b = new Bootstrap();
            b.group(group)
                    .channel(NioSocketChannel.class)
                    .option(ChannelOption.RCVBUF_ALLOCATOR,new FixedRecvByteBufAllocator(1024))
                    .handler(new LoggingHandler(LogLevel.INFO))
                    .handler(new ClientInitializer());
            Channel f = b.connect(host,port).sync().channel();
            ChannelFuture lastWriteFuture = null;
            String[] li = new String[]{"1", "2", "3", "4", "5"};
            for (String s : li) {
                String dz = String.format("C:/Users/zkd/Desktop/%s.jpg", s);
                System.out.println("地址：" + dz);
                InputStream inputStream = new FileInputStream(dz);
                BufferedInputStream bufferedInputStream = new BufferedInputStream(inputStream);
                byte[] buffer = new byte[1024];
                //从文件中按字节读取内容，到文件尾部时read方法将返回-1 发送图片数据
                while (bufferedInputStream.read(buffer) != -1) {
                    f.writeAndFlush(Unpooled.copiedBuffer(buffer));
                }
                // 最后添加]END结束一次数据发送
                lastWriteFuture = f.writeAndFlush(Unpooled.copiedBuffer("|END".getBytes(CharsetUtil.ISO_8859_1)));
            }

            if (lastWriteFuture != null) {
                lastWriteFuture.sync();
            }
        } finally {
            group.shutdownGracefully();
        }

    }
}
